﻿using System.ComponentModel.DataAnnotations;

namespace WebAPI.Filters;

/// <summary>
/// 密码
/// </summary>
public class PasswordAttribute : ValidationAttribute
{
    /// <summary>
    /// 默认的错误提示信息
    /// </summary>
    private const string Error = "无效的英文字母、数字和特殊字符的组合";

    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value is null) return new ValidationResult("参数值为 null");
        // 验证参数逻辑 value 是需要验证的值，而 validationContext 中包含了验证相关的上下文信息，这里可自己封装一个验证格式的 FormatValidation 类
        return IsCombinationOfEnglishNumberSymbol(value as string, 8) ?
            //验证成功返回 success
            ValidationResult.Success :
            //不成功 提示验证错误的信息
            new ValidationResult(ErrorMessage ?? Error);
    }
        
    /// <summary>
    /// 只包含英文字母、数字和特殊字符的组合
    /// </summary>
    /// <returns></returns>
    private static bool IsCombinationOfEnglishNumberSymbol(string? input, int? minLength = null, int? maxLength = null)
    {
        if (string.IsNullOrEmpty(input))
        {
            return false;
        }
        var pattern = @"(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z\d]).";
        if (minLength is null && maxLength is null)
            pattern = $"^{pattern}+$";
        else if (minLength != null && maxLength is null)
            pattern = $"^{pattern}{{{minLength},}}$";
        else if (minLength is null && maxLength != null)
            pattern = $"^{pattern}{{1,{maxLength}}}$";
        else
            pattern = $"^{pattern}{{{minLength},{maxLength}}}$";
        return System.Text.RegularExpressions.Regex.IsMatch(input, pattern);
    }
}